# apps/imports/views.py
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.utils import timezone
from rest_framework import viewsets, filters, status, permissions
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from django.db.models import Sum

from . import models
from .models import ImportLog
from .serializers import ImportLogSerializer, ImportLogListSerializer, ImportLogCreateSerializer
from .filters import ImportLogFilter  # 可选：高级过滤（见下方说明）

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

from ..common.mixins import TenantViewSetMixin


class ImportLogViewSet(TenantViewSetMixin, viewsets.ModelViewSet):
    """
    试题导入日志管理视图集
    提供：列表、详情、创建、更新、删除、自定义操作
    """
    queryset = ImportLog.objects.all().select_related('importer').order_by('-created_at')
    permission_classes = [permissions.IsAuthenticated, permissions.DjangoModelPermissions]
    filter_backends = [
        DjangoFilterBackend,
        filters.SearchFilter,
        filters.OrderingFilter,
    ]
    search_fields = ['file_name', 'importer__username', 'importer__first_name', 'importer__last_name']
    ordering_fields = ['created_at', 'started_at', 'completed_at', 'total_count', 'success_count', 'status']
    ordering = ['-created_at']

    def get_serializer_class(self):
        """
        根据不同动作使用不同的序列化器
        """
        if self.action == 'list':
            return ImportLogListSerializer
        elif self.action == 'create':
            return ImportLogCreateSerializer
        return ImportLogSerializer

    def perform_create(self, serializer):
        """
        创建时自动设置当前用户为 importer
        """
        serializer.save(importer=self.request.user)
    def get_queryset(self):
        qs = super().get_queryset()
        user = self.request.user

        # 只有超级管理员能看所有人的记录
        if not user.is_superuser:
            # 普通用户只能看自己的（但前提是：他已经通过了 view_importlog 权限检查！）
            qs = qs.filter(importer=user)

        return qs
    @action(detail=True, methods=['post'], url_path='mark-processing', permission_classes=[IsAuthenticated])
    def mark_processing(self, request, pk=None):
        """
        自定义 action：标记为“处理中”
        URL: /api/imports/import-logs/{id}/mark-processing/
        """
        log = self.get_object()

        if log.status != 'pending':
            return Response(
                {"error": "只有“等待”状态的日志才能标记为处理中。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        log.status = 'processing'
        log.started_at = timezone.now()
        log.save(update_fields=['status', 'started_at'])

        serializer = self.get_serializer(log)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(detail=True, methods=['post'], url_path='mark-completed')
    def mark_completed(self, request, pk=None):
        log = self.get_object()
        if log.status != 'processing':
            return Response(
                {"error": "只有“处理中”状态的日志才能标记为完成。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        serializer = ImportLogSerializer(log, data=request.data, partial=True)
        if serializer.is_valid():
            # 使用 serializer.save() 并传入额外字段
            instance = serializer.save(
                status='completed',
                completed_at=timezone.now(),
                fail_count=serializer.instance.total_count - serializer.validated_data.get('success_count', serializer.instance.success_count)
            )
            return Response(ImportLogSerializer(instance).data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    @action(detail=True, methods=['post'], url_path='mark-failed', permission_classes=[IsAuthenticated])
    def mark_failed(self, request, pk=None):
        """
        自定义 action：标记为“失败”
        可传入 error_log
        URL: /api/imports/import-logs/{id}/mark-failed/
        """
        log = self.get_object()
        if log.status not in ['pending', 'processing']:
            return Response(
                {"error": "只有“等待”或“处理中”状态的日志才能标记为失败。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        log.status = 'failed'
        log.completed_at = timezone.now()
        if 'error_log' in request.data:
            log.error_log = request.data['error_log']
        log.save(update_fields=['status', 'completed_at', 'error_log'])

        return Response(ImportLogSerializer(log).data, status=status.HTTP_200_OK)


    @method_decorator(cache_page(60 * 5), name='stats')
    @action(detail=False, methods=['get'], url_path='stats', permission_classes=[IsAuthenticated])
    def stats(self, request):
        """
        统计信息：总导入数、成功总数、失败总数、最近导入等
        URL: /api/imports/import-logs/stats/
        """
        total = self.filter_queryset(self.get_queryset()).count()
        success_total = self.get_queryset().aggregate(
            total=Sum('success_count')
        )['total'] or 0
        fail_total = self.get_queryset().aggregate(
            total=Sum('fail_count')
        )['total'] or 0

        latest = self.get_queryset().first()
        latest_data = None
        if latest:
            latest_data = ImportLogListSerializer(latest).data

        data = {
            "total_imports": total,
            "total_success": success_total,
            "total_fail": fail_total,
            "latest_import": latest_data,
            "summary": f"共导入 {success_total} 条试题，失败 {fail_total} 条。"
        }
        return Response(data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'], url_path='my-latest', permission_classes=[IsAuthenticated])
    def my_latest(self, request):
        """
        获取当前用户的最近一次导入记录
        URL: /api/imports/import-logs/my-latest/
        """
        log = self.get_queryset().filter(importer=request.user).first()
        if log:
            return Response(ImportLogSerializer(log).data)
        return Response({}, status=status.HTTP_404_NOT_FOUND)